package controllers

import (
	"encoding/json"
	"net/http"
	"github.com/astaxie/beego"
	"github.com/gorilla/websocket"
	//"samples/WebIM/models"
	//"net/http"
	//"log"
)

type WebSocketController struct {
	beego.Controller
}

var upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
	ReadBufferSize:  1024, //设置读的缓存大小为1024
	WriteBufferSize: 1024, //设置写的缓存大小为1024
}

func Join(w http.ResponseWriter, r *http.Request, nick string) {
	// Safe check.
	ws, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		beego.Error(err)
		return
	}
	messages := ""
	for {
		_, p, err := ws.ReadMessage()
		if err != nil {
			return
		}
		messages = string(p)
		beego.Info("收到的消息是：",messages)
		messageChan <- newClient(EVENT_MESSAGE,nick,messages,ws)
		//messageChan <- messages
	}
}

func broadcastWebSocket(client Client)  {
	data, err := json.Marshal(client.Content)
	if err != nil {
		beego.Error("Fail to marshal event:", err)
		return
	}
	ws := client.Conn
	ws.WriteMessage(websocket.TextMessage, data)
}
